package com.joy.joyusers.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joy.joyusers.model.domain.User;
import com.joy.joyusers.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热任务
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private UserService userService;

    // 重点用户，这里就先写死
    private List<Long> mainUserList = Arrays.asList(1L);

    // 缓存预热
    // 参数秒分时日月年：现在是每天的23:59:00执行
    @Scheduled(cron = "0 5 17 * * *")
    public void doCacheRecommend() {
        // 得到Loack对象
        RLock lock = redissonClient.getLock("partner:precachejob:docache:lock");
        // 尝试获取锁，等待时间0秒就好，只需要一个机器执行一次, 锁过期时间30秒
        try {
            if(lock.tryLock(0,-1,TimeUnit.MILLISECONDS)) {
                System.out.println("我拿到锁啦!!!");
                Thread.sleep(1000000);
                System.out.println("getLock" + Thread.currentThread().getId());
                // 遍历重点用户列表，从设计上来说可以设置一个标识是不是重点用户，去数据库遍历出来列表
                for (Long userid : mainUserList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("partner:user:recommend:%s", userid);
                    // 创建一个redistemplate操作对象 <String, Object>
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    // 写缓存
                    try {
                        valueOperations.set(redisKey, userPage, 60000, TimeUnit.MILLISECONDS);  // 可能出现缓存雪崩问题
                    } catch (Exception e) {
                        log.info("redis set key error",e);
                    }
                }

            }
        } catch (InterruptedException e) {
            log.error("Redis set key error", e);
        } finally {                                 // 一定要在finally里面执行判断锁然后释放的逻辑
            // 判断锁是不是当前线程的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unloack"+ Thread.currentThread().getId());
                // 释放锁
                lock.unlock();
            }
        }

    }






}
